package com.space9.search.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.space9.search.dao.SearchDao;
import com.space9.search.pojo.Item;
import com.space9.search.pojo.SearchResult;

@Repository
public class SearchDaoImpl implements SearchDao {
	
	@Autowired
	private RestHighLevelClient rhlClient;

	@Override
	public SearchResult search(SearchRequest searchRequest) throws Exception {
		//返回值对象
		SearchResult result = new SearchResult();
		//根据查询条件查询索引库
		SearchResponse searchResponse = rhlClient.search(searchRequest);
		//取查询结果
		SearchHits hits = searchResponse.getHits();
		//取查询结果总数量
		result.setRecordCount(searchResponse.getHits().getTotalHits());
		//商品列表
		List<Item> itemList = new ArrayList<>();
		
		
		//取商品列表
		for(SearchHit hit : hits.getHits())
		{
			//打印商品列表
		    System.out.println(hit.getSourceAsString());
		    Item item = new Item();
		    Map<String, Object> hitMap = hit.getSourceAsMap();
		    item.setId((String) hitMap.get("id"));
			
			//取高亮显示
			Map<String, HighlightField> highlightFields = hit.getHighlightFields();
		    HighlightField highlight = highlightFields.get("item_title"); 
		    Text[] fragments = highlight.fragments();  
		    String fragmentString = fragments[0].string();
		    System.out.println(fragmentString);
		    String title = "";
			if (fragments != null && fragments.length>0) {
				title = fragmentString;
			} else {
				title = (String) hitMap.get("item_title");
			}
			
			
		    item.setTitle(title);
			item.setImage((String) hitMap.get("item_image"));
			item.setPrice((Integer) hitMap.get("item_price"));
			item.setSell_point((String) hitMap.get("item_sell_point"));
			item.setCategory_name((String) hitMap.get("item_category_name"));
			item.setItem_des((String) hitMap.get("item_des"));

			System.out.println(hit.getSourceAsMap().get("id"));
		    //添加的商品列表
			itemList.add(item);
		}
		result.setItemList(itemList);
		return result;
	}

}
